<template>
  <div class="line-chart-card">
    <div class="card-header">
      <el-date-picker
        v-model="selectedYear"
        type="year"
        placeholder="选择年份"
        format="YYYY"
        value-format="YYYY"
        @change="handleYearChange"
      />
    </div>
    <div class="card-content">
      <div ref="chartContainer" class="chart-container"></div>
    </div>
  </div>

  <el-dialog
    destroy-on-close
    :close-on-click-modal="false"
    v-model="catInvoiceDialog"
    title="账单查询"
    width="1200"
  >
    <cat-invoice-list :filters="catInvoiceFilters" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { invoiceStatisticsDayOfMonthApi, invoiceStatisticsMonthOfYearApi } from '@/api/invoice-api'
import type { ResultData } from '@/api/service'
import type { InvoiceStatisticsDayOfMonth } from '@/type/invoice-types'
import CatInvoiceList from '@/views/invoice/CatInvoiceList.vue'

// 图表实例
const chartInstance = ref<ECharts | null>(null)
const chartContainer = ref<HTMLDivElement | null>(null)

const catInvoiceDialog = ref<boolean>(false)
const catInvoiceFilters = ref<any>({})

// 日期选择
const selectedYear = ref<string>(getCurrentYear())

// 获取当前月份
function getCurrentYear() {
  const now = new Date()
  return now.getFullYear().toString()
}

// 处理月份变化
function handleYearChange(value: string | null) {
  if (value) {
    updateChartData()
  }
}

// 初始化图表
function initChart() {
  if (chartContainer.value) {
    chartInstance.value = echarts.init(chartContainer.value)
    updateChartData()
  }
}

// 更新图表数据
function updateChartData() {
  if (!chartInstance.value) return

  invoiceStatisticsMonthOfYearApi(selectedYear.value).then(
    (res: ResultData<InvoiceStatisticsDayOfMonth>) => {
      const data = res.data
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line', // 指示器类型，'line'(直线) | 'shadow'(阴影) | 'cross'(十字准星)
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: data.x.map((item) => `${item}月`)
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            data: data.y,
            type: 'line',
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 2
            },
            itemStyle: {
              color: '#409eff'
            },
            label: {
              show: true, // 显示标签
              position: 'top', // 标签位置，可选 'top', 'bottom', 'left', 'right'
              formatter: '{c}', // 显示数据值，{c} 表示数据值
              // 如果需要格式化为金额，可以使用：
              // formatter: '¥{c}'
              color: '#409eff', // 标签颜色
              fontSize: 12,
              fontWeight: 'bold'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(64, 158, 255, 0.3)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(64, 158, 255, 0.05)'
                  }
                ]
              }
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        }
      }

      chartInstance.value!.on('click', function (params: any) {
        // params 是事件回调函数的参数对象，包含了点击点的详细信息
        // 确保点击的是“数据项”（即折线图上的一个点）
        if (params.componentType === 'series' && params.seriesType === 'line') {
          const year = selectedYear.value
          const month = params.name.replace("月", "")
          const tDate = new Date(Number.parseInt(year), Number.parseInt(month), 0)
          catInvoiceFilters.value.tranDatetime = {
            operator: "BETWEEN",
            value: [
              `${year}-${month}-01 00:00:00`,
              `${year}-${month}-${tDate.getDate()} 23:59:59`
            ]
          }
          catInvoiceFilters.value.tranErType = {
            operator: "EQ",
            value: "支出"
          }
          catInvoiceDialog.value = true
        }
      })
      chartInstance.value!.setOption(option)
    }
  )
}

// 监听窗口大小变化
function handleResize() {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

// 监听月份变化
watch(selectedYear, () => {
  updateChartData()
})
</script>

<style scoped>
.line-chart-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: end;
  align-items: center;
}

.card-content {
  flex: 1;
  padding: 0 16px 16px 16px;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
  min-height: 200px;
}
</style>
